﻿unit MainForm;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, 
  Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
  Vcl.ComCtrls, ServerController, System.UITypes, Vcl.Menus, System.DateUtils;

type
  TfrmMain = class(TForm)
    pnlTop: TPanel;
    lblPort: TLabel;
    edtPort: TEdit;
    btnStart: TButton;
    btnStop: TButton;
    lblStatus: TLabel;
    pnlLog: TPanel;
    lblLog: TLabel;
    memLog: TMemo;
    StatusBar: TStatusBar;
    pnlBottom: TPanel;
    btnRestart: TButton;
    btnModules: TButton;
    btnSettings: TButton;
    Timer1: TTimer;
    PopupMenu1: TPopupMenu;
    Clear1: TMenuItem;
    Copy1: TMenuItem;
    N1: TMenuItem;
    SelectAll1: TMenuItem;
    procedure btnStartClick(Sender: TObject);
    procedure btnStopClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure btnRestartClick(Sender: TObject);
    procedure btnModulesClick(Sender: TObject);
    procedure btnSettingsClick(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
    procedure Clear1Click(Sender: TObject);
    procedure Copy1Click(Sender: TObject);
    procedure SelectAll1Click(Sender: TObject);
    procedure edtPortKeyPress(Sender: TObject; var Key: Char);
  private
    FServerController: TServerController;
    FStartTime: TDateTime;
    FRequestCount: Integer;
    procedure UpdateUI;
    procedure Log(const Msg: string);
    procedure UpdateStatusBar;
    procedure LoadSettings;
    procedure SaveSettings;
  public
    { Public declarations }
  end;

var
  frmMain: TfrmMain;

implementation

{$R *.dfm}

uses
  System.IniFiles, Vcl.Clipbrd, ModulesForm, SettingsForm;

procedure TfrmMain.btnStartClick(Sender: TObject);
begin
  try
    Screen.Cursor := crHourGlass;
    try
      FServerController.Port := StrToIntDef(edtPort.Text, 9990);
      FServerController.Start;
      FStartTime := Now;
      FRequestCount := 0;
      Log('✓ Server started successfully on port ' + edtPort.Text);
      Log('✓ Server listening on: http://localhost:' + edtPort.Text);
      UpdateUI;
      SaveSettings;
    finally
      Screen.Cursor := crDefault;
    end;
  except
    on E: Exception do
    begin
      Log('✗ Error starting server: ' + E.Message);
      MessageDlg('Failed to start server: ' + E.Message, mtError, [mbOK], 0);
    end;
  end;
end;

procedure TfrmMain.btnStopClick(Sender: TObject);
begin
  try
    Screen.Cursor := crHourGlass;
    try
      FServerController.Stop;
      Log('✓ Server stopped successfully');
      UpdateUI;
    finally
      Screen.Cursor := crDefault;
    end;
  except
    on E: Exception do
    begin
      Log('✗ Error stopping server: ' + E.Message);
      MessageDlg('Failed to stop server: ' + E.Message, mtError, [mbOK], 0);
    end;
  end;
end;

procedure TfrmMain.btnRestartClick(Sender: TObject);
begin
  if FServerController.IsRunning then
  begin
    btnStopClick(Sender);
    // 使用Timer来延迟重启，确保服务器完全停止
    Timer1.Interval := 1000;
    Timer1.Tag := 1; // 标记为重启操作
    Timer1.Enabled := True;
  end
  else
  begin
    btnStartClick(Sender);
  end;
end;

procedure TfrmMain.btnModulesClick(Sender: TObject);
begin
  // 显示模块管理窗口
  with TfrmModules.Create(Self) do
  try
    ShowModal;
  finally
    Free;
  end;
end;

procedure TfrmMain.btnSettingsClick(Sender: TObject);
begin
  // 显示设置窗口
  with TfrmSettings.Create(Self) do
  try
    ShowModal;
    if ModalResult = mrOk then
    begin
      SaveSettings;
    end;
  finally
    Free;
  end;
end;

procedure TfrmMain.FormCreate(Sender: TObject);
begin
  // 初始化
  FServerController := TServerController.Create(9990);
  FStartTime := Now;
  FRequestCount := 0;
  
  // 加载设置
  LoadSettings;
  
  // 更新界面
  UpdateUI;
  
  // 启动状态更新定时器
  Timer1.Enabled := True;
  
  Log('🚀 Application started at ' + FormatDateTime('yyyy-mm-dd hh:nn:ss', Now));
  Log('💡 Ready to start server on port ' + edtPort.Text);
end;

procedure TfrmMain.FormDestroy(Sender: TObject);
begin
  // 停止服务器
  if FServerController.IsRunning then
    FServerController.Stop;
    
  // 保存设置
  SaveSettings;
    
  // 释放资源
  FServerController.Free;
  
  Log('👋 Application shutdown at ' + FormatDateTime('yyyy-mm-dd hh:nn:ss', Now));
end;

procedure TfrmMain.Log(const Msg: string);
begin
  // 线程安全的日志记录
  TThread.Queue(nil, procedure
    begin
      memLog.Lines.Add(Format('[%s] %s', 
        [FormatDateTime('hh:nn:ss.zzz', Now), Msg]));
        
      // 自动滚动到底部
      memLog.Perform(EM_LINESCROLL, 0, memLog.Lines.Count);
    end);
end;

procedure TfrmMain.UpdateUI;
begin
  // 更新按钮状态
  btnStart.Enabled := not FServerController.IsRunning;
  btnStop.Enabled := FServerController.IsRunning;
  btnRestart.Enabled := True;
  edtPort.Enabled := not FServerController.IsRunning;
  
  // 更新状态标签
  if FServerController.IsRunning then
  begin
    lblStatus.Caption := 'Status: Running';
    lblStatus.Font.Color := clGreen;
  end
  else
  begin
    lblStatus.Caption := 'Status: Stopped';
    lblStatus.Font.Color := clRed;
  end;
  
  // 更新状态栏
  UpdateStatusBar;
end;

procedure TfrmMain.UpdateStatusBar;
var
  Uptime: string;
begin
  if FServerController.IsRunning then
  begin
    Uptime := FormatDateTime('hh:nn:ss', Now - FStartTime);
    StatusBar.Panels[0].Text := Format('Running on port %s - Uptime: %s', 
      [edtPort.Text, Uptime]);
    StatusBar.Panels[1].Text := Format('Requests: %d', [FRequestCount]);
  end
  else
  begin
    StatusBar.Panels[0].Text := 'Server stopped';
    StatusBar.Panels[1].Text := '';
  end;
  
  StatusBar.Panels[2].Text := FormatDateTime('hh:nn:ss', Now);
end;

procedure TfrmMain.Timer1Timer(Sender: TObject);
begin
  // 更新状态栏时间
  UpdateStatusBar;
  
  // 处理重启标记
  if Timer1.Tag = 1 then
  begin
    Timer1.Tag := 0;
    Timer1.Enabled := False;
    btnStartClick(Self);
  end;
end;

procedure TfrmMain.LoadSettings;
var
  IniFile: TIniFile;
begin
  IniFile := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini'));
  try
    edtPort.Text := IniFile.ReadString('Server', 'Port', '8080');
    // 可以加载其他设置...
  finally
    IniFile.Free;
  end;
end;

procedure TfrmMain.SaveSettings;
var
  IniFile: TIniFile;
begin
  IniFile := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini'));
  try
    IniFile.WriteString('Server', 'Port', edtPort.Text);
    // 可以保存其他设置...
  finally
    IniFile.Free;
  end;
end;

procedure TfrmMain.Clear1Click(Sender: TObject);
begin
  memLog.Clear;
end;

procedure TfrmMain.Copy1Click(Sender: TObject);
begin
  if memLog.SelText <> '' then
    Clipboard.AsText := memLog.SelText
  else
    Clipboard.AsText := memLog.Text;
end;

procedure TfrmMain.SelectAll1Click(Sender: TObject);
begin
  memLog.SelectAll;
end;

procedure TfrmMain.edtPortKeyPress(Sender: TObject; var Key: Char);
begin
  // 只允许数字输入
  if not (Key in ['0'..'9', #8]) then
    Key := #0;
end;

end.